﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace FlightSearchServer
{
    class SearchServerHost
    {
        public const int CLIENT_PORT_ARG = 0;

        public const int SELLERS_PORT_ARG = 1;

        public const int LOG_FILE_NAME_ARG = 2;

        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine( "Error. Incorrect input");
                Console.WriteLine("Expected: <clients port> <sellers port> <log file>");
                return;
            }
            Console.WriteLine("Flights search server");
            Console.WriteLine("Press any key to start");
            Console.ReadLine();

            using( ServiceHost registrationHost = new ServiceHost( typeof( RegistrationService),
                    new Uri(String.Format("http://localhost:{0}/services/{1}", args[SELLERS_PORT_ARG], "FlightsSearchReg"))),
                   searchHost = new ServiceHost( typeof(SearchService),
                    new Uri(String.Format("http://localhost:{0}/services/{1}", args[CLIENT_PORT_ARG], "FlightSearch")))) 
            {
                Console.WriteLine( "Starting service for sellers registration, binded to port {0}", args[SELLERS_PORT_ARG]);
                foreach( ServiceEndpoint endpoint in registrationHost.Description.Endpoints)
                {
                    Console.WriteLine( "Endpoint ({0}), listening at address: {1}", endpoint.Name, endpoint.Address);
                }
                registrationHost.Open( );
                Console.WriteLine( "<=======================================================>");
                Console.WriteLine( "Starting service for clients flights search, binded to port {0}", args[CLIENT_PORT_ARG]);
                foreach (ServiceEndpoint endpoint in searchHost.Description.Endpoints)
                {
                    Console.WriteLine("Endpoint ({0}), listening at address: {1}", endpoint.Name, endpoint.Address);
                    endpoint.Behaviors.Add(new LoggerBehavior( args[LOG_FILE_NAME_ARG]));
                }
                //searchHost.Description.Behaviors.Add(  new CacheBehavior( ));
                searchHost.Open( );
                Console.WriteLine( "Press anykey to exit");
                Console.ReadLine( );
            }
        }
    }
}
